﻿using System.Collections.Generic;
using System.Text;
using UnityEngine;


namespace RStudio.UIFramwork
{
    /// <summary>
    /// 栈记录
    /// </summary>
    public class UIModuleStack
    {
        public UIModuleStack()
        {
            BackStack = new Stack<UIEventArg>();
        }

        /// <summary>
        /// 回退栈
        /// </summary>
        public Stack<UIEventArg> BackStack { get; private set; }


        /// <summary>
        /// 推送至栈
        /// </summary>
        /// <param name="uiEvent"></param>
        public void Push(UIEventArg uiEvent)
        {
            bool isPeek = Peek(out UIEventArg newEventArg);
            if (isPeek)
            {
                if (uiEvent.UIBase == newEventArg.UIBase) return;
                if (uiEvent.Type == newEventArg.Type) return;
            }

            this.BackStack.Push(uiEvent);
            Debug.Log($"<b>[Stack]</b>" +
                $"PUSH | 添置后栈大小: {this.BackStack.Count}");
        }

        /// <summary>
        /// 取出
        /// </summary>
        /// <param name="output"></param>
        /// <returns></returns>
        public bool Pop(out UIEventArg output)
        {
            output = null;

            if (this.BackStack == null) return false;
            if (this.BackStack.Count == 0) return false;

            bool isSuccess = this.BackStack.TryPop(out output);
            if (isSuccess)
            {
                Debug.Log($"<b>[Stack]</b>" +
                    $"Pop成功: {output.Type}, 弹出后栈大小: {this.BackStack.Count}");
            }

            return isSuccess;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="output"></param>
        /// <returns></returns>
        public bool Peek(out UIEventArg output)
        {
            output = null;

            if (this.BackStack == null) return false;
            if (this.BackStack.Count == 0) return false;

            bool isSuccess = this.BackStack.TryPeek(out output);

            return isSuccess;
        }

        /// <summary>
        /// 打印日志
        /// </summary>
        public void DebugStack()
        {
            StringBuilder sBuilder = new();

            sBuilder.AppendLine($"STACK 栈信息");
            foreach (var item in BackStack)
            {
                sBuilder.AppendLine($"{item.UIBase} {item.UIEventType} {item.Type}");
            }

            UnityEngine.Debug.Log(sBuilder.ToString());
        }
    }
}
